package just.stuff.morsels.ui.morsel;

import just.stuff.morsels.MorselApplication;
import just.stuff.morsels.objects.Morsel;
import just.stuff.morsels.ui.BasePage;
import just.stuff.morsels.util.UpdateController;

import org.apache.wicket.PageParameters;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

public class MorselPage extends BasePage {

	public static final String EDIT_PARAM = "edit";
	public static final String ID_PARAM = "id";
	
	@SuppressWarnings( "all")
	private boolean edited;
	
	/**
	 * Display root morsel by default. 
	 */
	public MorselPage() {
		this( MorselApplication.dataSource().getRootMorsel(), false );
	}
	
	public MorselPage( PageParameters params ) {
		this( MorselApplication.dataSource().load( params.get( ID_PARAM).toString() ),
				params.getAsBoolean( EDIT_PARAM, false ) );
	}

	/**
	 * Internal non-bookmarkable constructor.
	 * @param morsel
	 * @param edited
	 */
	private MorselPage( Morsel morsel, boolean edited ) {
		this.edited = morsel.getId() == null ? true : edited;

		UpdateController editController = new UpdateController();
		final IModel<Boolean> editModel = editController.wrap( new PropertyModel<Boolean>( this, "edited"));

		DisplayMorselPanel display = new DisplayMorselPanel( "display", morsel, editModel );
		display.setOutputMarkupId( true ).setOutputMarkupPlaceholderTag( true );
		editController.registerListener( display );
		add( display );

		EditMorselPanel edit = new EditMorselPanel( "edit", morsel, editModel );
		edit.setOutputMarkupId( true ).setOutputMarkupPlaceholderTag( true );
		editController.registerListener( edit);
		add( edit );
		
	}
	
}
